﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PokerClient.VisualDisp;
using PokerClient.Connection.Interfaces;

namespace PokerClient.Connection.CommandHandlers
{
	class tableHandler : absHandler
	{
		
		TableErrors terror;
		Dictionary<String, TableIdent> tablelist = new Dictionary<String, TableIdent>();
		Lobby lobby;
		String message;
		Client myClient;
		public tableHandler(Lobby lobby,Client myClient)
		{
			this.lobby = lobby;
			this.myClient = myClient;
		}
		public override string work()
		{
			String ans = "";
			switch(commands[0].ToUpper())
			{
				case "JOINTABLE-FAIL":
					ans = commands[1];
					terror = TableErrors.JOIN_FAILURE;
					//myClient.sTable = "-1";
					break;
				case "JOINTABLE-ACK":
					ans = "Success";
					terror = TableErrors.JOIN_SUCCESS;					
					break;
				case  "TABLELIST":
					tableSorter();
					lobby.tables = this.tablelist;
					terror = TableErrors.LISTTABLES;
					break;					
			}
			return (message = ans);
		}
	
		
		private void tableSorter()
		{
			char[] c = {'<','>'};
			for (int i = 1; i < commands.Length; i++)
			{
				TableIdent t;
				if (commands[i] != "")
				{
					String[] temp = commands[i].Split(c);
					String key = "";
					tableArranger(temp, out key, out t);
					this.tablelist.Add(key, t);
				}
			}
		}

		private void tableArranger(String[] details,out String key,out TableIdent t)
		{
			int i = details[1].LastIndexOf(':');
			int j = details[3].LastIndexOf(':');
			int k = details[5].LastIndexOf(':');
			t = new TableIdent();
			key = details[1].Substring(i+1);
			t.max = details[3].Substring(j+1);
			t.min = details[5].Substring(k+1);
		}
		public override void assignCommand(string commands)
		{
			if (commands.Contains("TableList"))
				this.commands = commands.Split(',',' ');
			else
			{
				this.commands = commands.Split(' ');
			}
		}

		public override void analyze()
		{

			lobby.updateStatus(message);
			switch(terror)
			{
				case TableErrors.JOIN_SUCCESS:
					lobby.changeScreen("Table");
					break;
				default:					
					break;
			}
		}
	}

	public class TableIdent
	{
		
		String maxBuy, minBuy;

		public String max
		{
			set
			{
				this.maxBuy = value;
			}
			get
			{
				return this.maxBuy;
			}
		}

		public String min
		{
			set
			{
				this.minBuy = value;
			}
			get
			{
				return this.minBuy;
			}
		}
	}

	enum TableErrors
	{
		JOIN_SUCCESS,
		JOIN_FAILURE,
		LISTTABLES,
		DEFAULT
	}
}
